<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量视频组合 - AI视频增强器</title>
    <link href="/static/css/style.css" rel="stylesheet">
    <style>
        .video-list-item {
            transition: all 0.2s ease;
        }
        .video-list-item:hover {
            background-color: #f8fafc;
        }
        .video-list-item.invalid {
            background-color: #fef2f2;
            border-color: #fca5a5;
        }
        .progress-bar {
            transition: width 0.3s ease;
        }
        .dragging {
            opacity: 0.5;
        }
        .drop-zone {
            border: 2px dashed #cbd5e0;
            background-color: #f7fafc;
        }
        .drop-zone.dragover {
            border-color: #4299e1;
            background-color: #ebf8ff;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen py-8">
    <div class="container mx-auto px-4">
        <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-6xl mx-auto">
            <!-- 页面标题 -->
            <div class="text-center mb-6">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">📂 批量视频组合</h1>
                <p class="text-gray-600 mb-3">扫描文件夹，智能排序，一键合并多个视频文件</p>
                <div class="space-x-4">
                    <a href="/" class="inline-flex items-center px-3 py-1 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        🏠 返回主页
                    </a>
                    <button id="help-btn" class="inline-flex items-center px-3 py-1 border border-blue-300 text-sm font-medium rounded-md text-blue-700 bg-blue-50 hover:bg-blue-100">
                        ❓ 使用帮助
                    </button>
                </div>
            </div>

            <!-- 帮助信息 -->
            <div id="help-panel" class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6" style="display: none;">
                <h3 class="text-lg font-medium text-blue-900 mb-3">📖 使用说明</h3>
                <div class="text-sm text-blue-800 space-y-2">
                    <p><strong>第1步：</strong> 输入包含视频文件的文件夹路径</p>
                    <p><strong>第2步：</strong> 点击"扫描文件夹"，系统会自动识别所有视频文件</p>
                    <p><strong>第3步：</strong> 系统会智能分析文件命名模式并自动排序</p>
                    <p><strong>第4步：</strong> 您可以手动调整排序或预览排序效果</p>
                    <p><strong>第5步：</strong> 点击"开始合并"，系统会将所有视频按顺序合并成一个文件</p>
                    <p><strong>第6步：</strong> 合并完成后，可以继续进入AI字幕和增强流程</p>
                </div>
                <div class="mt-3 p-3 bg-white rounded border">
                    <p class="text-sm font-medium text-gray-900 mb-1">支持的命名格式：</p>
                    <div class="text-xs text-gray-700 space-y-1">
                        <p>• 数字序列：1.mp4, 2.mp4, 10.mp4</p>
                        <p>• 章节格式：1-1.mp4, 1-2.mp4, 2-1.mp4</p>
                        <p>• 前缀序列：video1.mp4, video2.mp4</p>
                        <p>• 日期时间：20241201_143000.mp4</p>
                        <p>• 中文编号：第1章第2节.mp4</p>
                    </div>
                </div>
            </div>

            <!-- 步骤1：文件夹选择 -->
            <div id="step1" class="mb-8">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">📁 第1步：选择视频文件夹</h2>
                <div class="bg-gray-50 p-4 rounded-lg">
                    <div class="space-y-4">
                        <div>
                            <label for="folder-path" class="block text-sm font-medium text-gray-700 mb-2">文件夹路径：</label>
                            <div class="flex space-x-2">
                                <input type="text" id="folder-path" 
                                       value="/Users/v9/Documents/workspace/v9/code/banyun/videos/0722/0722-cat-video-v1"
                                       placeholder="例如：/Users/username/Videos/course"
                                       class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                <button id="browse-folder" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
                                    📂 浏览
                                </button>
                                <button id="scan-folder" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                                    🔍 扫描文件夹
                                </button>
                            </div>
                            <p class="mt-1 text-xs text-gray-500">支持拖拽文件夹到输入框，或手动输入文件夹路径</p>
                        </div>
                        
                        <div class="flex items-center space-x-4">
                            <label class="flex items-center">
                                <input type="checkbox" id="recursive-scan" class="mr-2">
                                <span class="text-sm text-gray-700">递归扫描子文件夹</span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤2：扫描结果 -->
            <div id="step2" class="mb-8" style="display: none;">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">📊 第2步：扫描结果</h2>
                <div class="bg-gray-50 p-4 rounded-lg">
                    <!-- 扫描统计 -->
                    <div id="scan-summary" class="mb-4 p-3 bg-white rounded border">
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
                            <div>
                                <div class="text-2xl font-bold text-blue-600" id="total-files">0</div>
                                <div class="text-xs text-gray-600">总文件数</div>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-green-600" id="valid-files">0</div>
                                <div class="text-xs text-gray-600">有效视频</div>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-purple-600" id="total-duration">0:00</div>
                                <div class="text-xs text-gray-600">总时长</div>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-orange-600" id="total-size">0 MB</div>
                                <div class="text-xs text-gray-600">总大小</div>
                            </div>
                        </div>
                    </div>

                    <!-- 命名模式分析 -->
                    <div id="naming-analysis" class="mb-4 p-3 bg-white rounded border">
                        <h4 class="font-medium text-gray-900 mb-2">🔍 命名模式分析</h4>
                        <div id="pattern-info" class="text-sm text-gray-700">
                            <p>检测到的模式：<span id="detected-pattern" class="font-medium">正在分析...</span></p>
                            <p>匹配置信度：<span id="pattern-confidence" class="font-medium">0%</span></p>
                            <p>推荐排序方法：<span id="recommended-sort" class="font-medium">自然排序</span></p>
                        </div>
                    </div>

                    <!-- 排序控制 -->
                    <div class="mb-4 flex flex-wrap items-center space-x-4">
                        <div class="flex items-center space-x-2">
                            <label for="sort-method" class="text-sm font-medium text-gray-700">排序方法：</label>
                            <select id="sort-method" class="px-2 py-1 border border-gray-300 rounded text-sm">
                                <option value="natural">智能排序（推荐）</option>
                                <option value="filename">文件名排序</option>
                                <option value="date_created">创建时间</option>
                                <option value="date_modified">修改时间</option>
                                <option value="size">文件大小</option>
                                <option value="duration">视频时长</option>
                            </select>
                        </div>
                        <button id="preview-sort" class="px-3 py-1 bg-yellow-600 text-white rounded text-sm hover:bg-yellow-700">
                            👁️ 预览排序
                        </button>
                        <button id="apply-sort" class="px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700">
                            ✅ 应用排序
                        </button>
                        <button id="batch-speed" class="px-3 py-1 bg-purple-600 text-white rounded text-sm hover:bg-purple-700">
                            ⚡ 批量设置速率
                        </button>
                    </div>

                    <!-- 视频文件列表 -->
                    <div id="video-list-container">
                        <div class="flex justify-between items-center mb-2">
                            <h4 class="font-medium text-gray-900">📋 视频文件列表</h4>
                            <div class="text-xs text-gray-500">拖拽重新排序</div>
                        </div>
                        <div id="video-list" class="space-y-2 max-h-96 overflow-y-auto border rounded p-2">
                            <!-- 视频文件项目将在这里动态生成 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤3：合并配置 -->
            <div id="step3" class="mb-8" style="display: none;">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">⚙️ 第3步：合并配置</h2>
                <div class="bg-gray-50 p-4 rounded-lg">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="output-filename" class="block text-sm font-medium text-gray-700 mb-1">输出文件名：</label>
                            <input type="text" id="output-filename" value="merged_video.mp4" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md">
                        </div>
                        <div>
                            <label for="merge-quality" class="block text-sm font-medium text-gray-700 mb-1">输出质量：</label>
                            <select id="merge-quality" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                                <option value="original">保持原质量（推荐）</option>
                                <option value="high">高质量（重新编码）</option>
                                <option value="medium">中等质量</option>
                                <option value="low">低质量（节省空间）</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- 背景音乐选项 -->
                    <div class="mt-6 p-4 bg-purple-50 border border-purple-200 rounded-lg">
                        <div class="flex items-center mb-3">
                            <input type="checkbox" id="add-background-music" class="mr-2 h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                            <label for="add-background-music" class="text-sm font-medium text-purple-900">🎵 添加背景音乐</label>
                        </div>
                        
                        <div id="background-music-options" class="space-y-4" style="display: none;">
                            <div>
                                <label for="background-music-file" class="block text-sm font-medium text-gray-700 mb-1">选择音乐文件：</label>
                                <input type="file" id="background-music-file" accept="audio/*" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                                <p class="mt-1 text-xs text-gray-500">支持 MP3, WAV, AAC, M4A 等音频格式</p>
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label for="music-volume" class="block text-sm font-medium text-gray-700 mb-1">背景音乐音量：</label>
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs text-gray-500">🔈</span>
                                        <input type="range" id="music-volume" min="0" max="100" value="30" 
                                               class="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
                                        <span class="text-xs text-gray-500">🔊</span>
                                        <span id="volume-display" class="text-sm font-medium text-gray-700 w-8">30%</span>
                                    </div>
                                </div>
                                
                                <div>
                                    <label for="music-start-time" class="block text-sm font-medium text-gray-700 mb-1">起始时间（秒）：</label>
                                    <input type="number" id="music-start-time" min="0" step="0.1" value="0" 
                                           placeholder="0"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                                    <p class="mt-1 text-xs text-gray-500">从音频文件的第几秒开始播放</p>
                                </div>
                                
                                <div>
                                    <label for="music-fade" class="block text-sm font-medium text-gray-700 mb-1">淡入淡出：</label>
                                    <select id="music-fade" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                                        <option value="none">无</option>
                                        <option value="in" selected>淡入（3秒）</option>
                                        <option value="out">淡出（3秒）</option>
                                        <option value="both">淡入淡出（3秒）</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="bg-blue-50 p-3 rounded border text-xs text-blue-800">
                                <p><strong>💡 说明：</strong></p>
                                <p>• 背景音乐会与视频原音混合，不会覆盖原声</p>
                                <p>• 最终长度以视频为准，背景音乐会自动循环或截断</p>
                                <p>• 建议音量设置在20%-40%之间以保持平衡</p>
                                <p>• 起始时间可设置从音频文件的指定时刻开始播放</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-4 flex justify-center">
                        <button id="start-merge" class="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium">
                            🚀 开始合并视频
                        </button>
                    </div>
                </div>
            </div>

            <!-- 步骤4：合并进度 -->
            <div id="step4" class="mb-8" style="display: none;">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">⏳ 第4步：合并进度</h2>
                <div class="bg-gray-50 p-4 rounded-lg">
                    <div class="mb-4">
                        <div class="flex justify-between text-sm text-gray-700 mb-1">
                            <span id="current-operation">准备中...</span>
                            <span id="progress-text">0%</span>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-3">
                            <div id="progress-bar" class="progress-bar bg-blue-600 h-3 rounded-full" style="width: 0%"></div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-center text-sm">
                        <div>
                            <div class="font-medium text-gray-900" id="current-file-index">0</div>
                            <div class="text-gray-600">当前文件</div>
                        </div>
                        <div>
                            <div class="font-medium text-gray-900" id="total-files-count">0</div>
                            <div class="text-gray-600">总文件数</div>
                        </div>
                        <div>
                            <div class="font-medium text-gray-900" id="elapsed-time">0:00</div>
                            <div class="text-gray-600">已用时间</div>
                        </div>
                        <div>
                            <div class="font-medium text-gray-900" id="estimated-time">--:--</div>
                            <div class="text-gray-600">预计剩余</div>
                        </div>
                    </div>
                    
                    <div class="mt-4 text-center">
                        <button id="cancel-merge" class="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700">
                            ⏹️ 取消合并
                        </button>
                    </div>
                </div>
            </div>

            <!-- 步骤5：完成 -->
            <div id="step5" class="mb-8" style="display: none;">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">✅ 第5步：完成</h2>
                <div class="bg-green-50 border border-green-200 p-4 rounded-lg">
                    <div class="text-center">
                        <div class="text-green-600 text-4xl mb-2">🎉</div>
                        <h3 class="text-lg font-medium text-green-900 mb-2">视频合并完成！</h3>
                        <p id="completion-summary" class="text-green-800 mb-4">
                            成功合并了 0 个视频文件，总时长 0:00
                        </p>
                        
                        <div class="space-x-4">
                            <button id="continue-to-ai" class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium">
                                🤖 继续AI处理
                            </button>
                            <button id="new-batch" class="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700">
                                🔄 新建批量任务
                            </button>
                            <a href="/" class="inline-block px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400">
                                🏠 返回主页
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // 全局变量
        let currentTaskId = null;
        let videoFiles = [];
        let scanSummary = {};
        let progressUpdateInterval = null;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeEventListeners();
        });

        function initializeEventListeners() {
            // 帮助按钮
            document.getElementById('help-btn').addEventListener('click', toggleHelp);
            
            // 文件夹操作
            document.getElementById('browse-folder').addEventListener('click', browseFolderDialog);
            document.getElementById('scan-folder').addEventListener('click', scanFolder);
            
            // 排序操作
            document.getElementById('sort-method').addEventListener('change', onSortMethodChange);
            document.getElementById('preview-sort').addEventListener('click', previewSort);
            document.getElementById('apply-sort').addEventListener('click', applySort);
            document.getElementById('batch-speed').addEventListener('click', setBatchSpeed);
            
            // 合并操作
            document.getElementById('start-merge').addEventListener('click', startMerge);
            document.getElementById('cancel-merge').addEventListener('click', cancelMerge);
            
            // 完成操作
            document.getElementById('continue-to-ai').addEventListener('click', continueToAI);
            document.getElementById('new-batch').addEventListener('click', newBatch);
            
            // 背景音乐相关
            document.getElementById('add-background-music').addEventListener('change', toggleBackgroundMusic);
            document.getElementById('music-volume').addEventListener('input', updateVolumeDisplay);
            
            // 文件夹路径拖拽支持
            setupFolderPathDragDrop();
        }

        function toggleHelp() {
            const helpPanel = document.getElementById('help-panel');
            helpPanel.style.display = helpPanel.style.display === 'none' ? 'block' : 'none';
        }

        function browseFolderDialog() {
            // 注意：现代浏览器出于安全考虑，无法直接浏览文件夹
            // 这里提供一个信息提示
            alert('由于浏览器安全限制，请手动输入文件夹路径。\\n\\n例如：\\n• macOS: /Users/username/Videos/course\\n• Windows: C:\\\\Users\\\\username\\\\Videos\\\\course\\n• Linux: /home/username/Videos/course');
        }

        function setupFolderPathDragDrop() {
            const folderPathInput = document.getElementById('folder-path');
            
            folderPathInput.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.classList.add('drop-zone', 'dragover');
            });

            folderPathInput.addEventListener('dragleave', function(e) {
                e.preventDefault();
                this.classList.remove('dragover');
            });

            folderPathInput.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('drop-zone', 'dragover');
                
                // 注意：出于安全原因，现代浏览器限制了对文件路径的访问
                // 这里只是一个占位符实现
                if (e.dataTransfer.files.length > 0) {
                    const file = e.dataTransfer.files[0];
                    if (file.webkitGetAsEntry && file.webkitGetAsEntry().isDirectory) {
                        this.value = file.webkitGetAsEntry().fullPath || file.name;
                    }
                }
            });
        }

        async function scanFolder() {
            const folderPath = document.getElementById('folder-path').value.trim();
            const recursive = document.getElementById('recursive-scan').checked;
            
            if (!folderPath) {
                alert('请输入文件夹路径');
                return;
            }

            // 显示加载状态
            showLoading('正在扫描文件夹...');

            try {
                const response = await fetch('/api/batch/scan-folder', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        folder_path: folderPath,
                        recursive: recursive
                    })
                });

                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.detail || '扫描失败');
                }

                videoFiles = data.video_files;
                scanSummary = data.summary;
                
                displayScanResults(data);
                showStep(2);
                
            } catch (error) {
                alert('扫描失败: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        function displayScanResults(data) {
            // 更新统计信息
            document.getElementById('total-files').textContent = data.summary.total_files;
            document.getElementById('valid-files').textContent = data.summary.valid_files;
            document.getElementById('total-duration').textContent = data.summary.total_duration_formatted;
            document.getElementById('total-size').textContent = data.summary.total_size_formatted;
            
            // 更新命名模式分析
            const namingAnalysis = data.naming_analysis;
            document.getElementById('detected-pattern').textContent = namingAnalysis.pattern || '未检测到模式';
            document.getElementById('pattern-confidence').textContent = Math.round(namingAnalysis.confidence * 100) + '%';
            document.getElementById('recommended-sort').textContent = getSortMethodName(namingAnalysis.recommended_method);
            
            // 设置推荐的排序方法
            if (namingAnalysis.recommended_method) {
                document.getElementById('sort-method').value = namingAnalysis.recommended_method;
            }
            
            // 显示视频文件列表
            displayVideoList(videoFiles);
        }

        function displayVideoList(files) {
            const listContainer = document.getElementById('video-list');
            listContainer.innerHTML = '';
            
            files.forEach((file, index) => {
                const item = createVideoListItem(file, index);
                listContainer.appendChild(item);
            });
            
            // 启用拖拽排序
            enableDragSort(listContainer);
        }

        function createVideoListItem(file, index) {
            const div = document.createElement('div');
            div.className = `video-list-item flex items-center p-3 border rounded ${file.is_valid ? 'border-gray-200' : 'border-red-200 invalid'}`;
            div.draggable = true;
            div.dataset.index = index;
            
            // 确保视频文件有speed属性，默认为1.0
            if (!file.speed) {
                file.speed = 1.0;
            }
            
            const resolution = file.resolution[0] > 0 ? `${file.resolution[0]}x${file.resolution[1]}` : '未知';
            const duration = file.duration > 0 ? formatDuration(file.duration) : '未知';
            const adjustedDuration = file.duration > 0 ? formatDuration(file.duration / file.speed) : '未知';
            const size = formatFileSize(file.size);
            
            div.innerHTML = `
                <div class="flex-shrink-0 w-8 text-center text-sm font-medium text-gray-500">
                    ${index + 1}
                </div>
                <div class="flex-1 ml-3">
                    <div class="flex items-center space-x-2">
                        <span class="font-medium ${file.is_valid ? 'text-gray-900' : 'text-red-600'}">${file.filename}</span>
                        ${file.is_valid ? '<span class="text-green-500 text-xs">✓</span>' : '<span class="text-red-500 text-xs">✗</span>'}
                    </div>
                    <div class="text-xs text-gray-500 mt-1">
                        ${resolution} • 原时长: ${duration} • 调整后: ${adjustedDuration} • ${size}
                        ${file.error_message ? `• <span class="text-red-500">${file.error_message}</span>` : ''}
                    </div>
                </div>
                <div class="flex-shrink-0 flex items-center space-x-2 mr-2">
                    <div class="flex items-center space-x-1">
                        <label class="text-xs text-gray-600">速率:</label>
                        <input type="number" 
                               class="speed-input w-16 px-1 py-1 border border-gray-300 rounded text-xs text-center"
                               value="${file.speed}" 
                               min="0.25" 
                               max="4.0" 
                               step="0.1"
                               data-index="${index}">
                        <span class="text-xs text-gray-500">x</span>
                    </div>
                </div>
                <div class="flex-shrink-0 cursor-move text-gray-400">
                    ⋮⋮
                </div>
            `;
            
            // 添加速率变化监听器
            const speedInput = div.querySelector('.speed-input');
            speedInput.addEventListener('change', function() {
                updateVideoSpeed(index, parseFloat(this.value));
            });
            
            speedInput.addEventListener('input', function() {
                // 实时更新显示的调整后时长
                const newSpeed = parseFloat(this.value) || 1.0;
                const adjustedDurationElement = div.querySelector('.text-xs.text-gray-500');
                const newAdjustedDuration = file.duration > 0 ? formatDuration(file.duration / newSpeed) : '未知';
                adjustedDurationElement.innerHTML = `
                    ${resolution} • 原时长: ${duration} • 调整后: ${newAdjustedDuration} • ${size}
                    ${file.error_message ? `• <span class="text-red-500">${file.error_message}</span>` : ''}
                `;
            });
            
            return div;
        }

        function enableDragSort(container) {
            let draggedElement = null;
            
            container.addEventListener('dragstart', function(e) {
                draggedElement = e.target.closest('.video-list-item');
                if (draggedElement) {
                    draggedElement.classList.add('dragging');
                }
            });
            
            container.addEventListener('dragend', function(e) {
                if (draggedElement) {
                    draggedElement.classList.remove('dragging');
                    draggedElement = null;
                }
            });
            
            container.addEventListener('dragover', function(e) {
                e.preventDefault();
            });
            
            container.addEventListener('drop', function(e) {
                e.preventDefault();
                
                if (!draggedElement) return;
                
                const dropTarget = e.target.closest('.video-list-item');
                if (dropTarget && dropTarget !== draggedElement) {
                    const draggedIndex = parseInt(draggedElement.dataset.index);
                    const targetIndex = parseInt(dropTarget.dataset.index);
                    
                    // 重新排序数组
                    const draggedFile = videoFiles[draggedIndex];
                    videoFiles.splice(draggedIndex, 1);
                    videoFiles.splice(targetIndex, 0, draggedFile);
                    
                    // 重新显示列表
                    displayVideoList(videoFiles);
                }
            });
        }

        function onSortMethodChange() {
            // 排序方法改变时，自动应用排序
            applySort();
        }

        async function previewSort() {
            const sortMethod = document.getElementById('sort-method').value;
            
            try {
                const response = await fetch('/api/batch/preview-sort', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        video_files: videoFiles,
                        sort_method: sortMethod
                    })
                });

                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.detail || '预览失败');
                }

                // 显示预览结果
                showSortPreview(data.preview);
                
            } catch (error) {
                alert('预览失败: ' + error.message);
            }
        }

        function showSortPreview(preview) {
            if (preview.total_changes === 0) {
                alert('排序后文件顺序没有变化');
                return;
            }
            
            let message = `排序预览：\\n\\n将有 ${preview.total_changes} 个文件的位置发生变化：\\n\\n`;
            
            preview.changes.slice(0, 10).forEach(change => {
                const direction = change.change > 0 ? '↓' : '↑';
                message += `${change.filename}: ${change.old_position} → ${change.new_position} ${direction}\\n`;
            });
            
            if (preview.changes.length > 10) {
                message += `\\n... 还有 ${preview.changes.length - 10} 个文件\\n`;
            }
            
            message += '\\n是否应用此排序？';
            
            if (confirm(message)) {
                applySort();
            }
        }

        async function applySort() {
            const sortMethod = document.getElementById('sort-method').value;
            
            try {
                const response = await fetch('/api/batch/preview-sort', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        video_files: videoFiles,
                        sort_method: sortMethod
                    })
                });

                const data = await response.json();
                
                if (response.ok && data.preview) {
                    // 应用排序结果
                    const sortedFiles = data.preview.sorted.map(item => {
                        return videoFiles.find(f => f.filename === item[1]);
                    });
                    
                    videoFiles = sortedFiles;
                    displayVideoList(videoFiles);
                    
                    // 自动进入下一步
                    showStep(3);
                }
                
            } catch (error) {
                alert('排序失败: ' + error.message);
            }
        }

        async function startMerge() {
            const outputFilename = document.getElementById('output-filename').value.trim();
            const mergeQuality = document.getElementById('merge-quality').value;
            const addBackgroundMusic = document.getElementById('add-background-music').checked;
            
            if (!outputFilename) {
                alert('请输入输出文件名');
                return;
            }
            
            const validFiles = videoFiles.filter(f => f.is_valid);
            if (validFiles.length === 0) {
                alert('没有有效的视频文件可以合并');
                return;
            }

            // 确保每个文件都有speed属性
            validFiles.forEach(file => {
                if (!file.speed) {
                    file.speed = 1.0;
                }
            });

            // 如果选择了背景音乐，检查文件是否选择
            let backgroundMusicFile = null;
            if (addBackgroundMusic) {
                const musicFileInput = document.getElementById('background-music-file');
                if (!musicFileInput.files || musicFileInput.files.length === 0) {
                    alert('请选择背景音乐文件');
                    return;
                }
                backgroundMusicFile = musicFileInput.files[0];
            }

            try {
                showStep(4);
                
                // 准备FormData以支持文件上传
                const formData = new FormData();
                formData.append('video_files', JSON.stringify(validFiles));
                formData.append('output_filename', outputFilename);
                formData.append('config', JSON.stringify({
                    merge_quality: mergeQuality,
                    background_music: addBackgroundMusic ? {
                        volume: parseFloat(document.getElementById('music-volume').value) / 100,
                        fade: document.getElementById('music-fade').value,
                        start_time: parseFloat(document.getElementById('music-start-time').value) || 0
                    } : null
                }));
                
                if (backgroundMusicFile) {
                    formData.append('background_music_file', backgroundMusicFile);
                }
                
                const response = await fetch('/api/batch/start-merge', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.detail || '启动合并失败');
                }

                currentTaskId = data.task_id;
                
                // 开始监控进度
                startProgressMonitoring();
                
            } catch (error) {
                alert('合并失败: ' + error.message);
                showStep(3);
            }
        }

        function startProgressMonitoring() {
            progressUpdateInterval = setInterval(updateProgress, 1000);
            updateProgress(); // 立即更新一次
        }

        async function updateProgress() {
            if (!currentTaskId) return;

            try {
                const response = await fetch(`/api/batch/task-status/${currentTaskId}`);
                const data = await response.json();
                
                if (response.ok && data.status) {
                    const status = data.status;
                    
                    // 更新进度显示
                    document.getElementById('current-operation').textContent = status.current_step || '处理中...';
                    document.getElementById('progress-text').textContent = Math.round(status.progress_percent) + '%';
                    document.getElementById('progress-bar').style.width = status.progress_percent + '%';
                    
                    document.getElementById('current-file-index').textContent = status.valid_files || 0;
                    document.getElementById('total-files-count').textContent = status.total_files || 0;
                    document.getElementById('elapsed-time').textContent = formatDuration(status.elapsed_time || 0);
                    document.getElementById('estimated-time').textContent = formatDuration(status.estimated_remaining || 0);
                    
                    // 检查是否完成
                    if (status.status === 'completed') {
                        clearInterval(progressUpdateInterval);
                        showCompletionStep(status);
                    } else if (status.status === 'error') {
                        clearInterval(progressUpdateInterval);
                        alert('合并失败: ' + (status.error_message || '未知错误'));
                        showStep(3);
                    } else if (status.status === 'cancelled') {
                        clearInterval(progressUpdateInterval);
                        alert('合并已取消');
                        showStep(3);
                    }
                }
                
            } catch (error) {
                console.error('获取进度失败:', error);
            }
        }

        async function cancelMerge() {
            if (!currentTaskId) return;
            
            if (confirm('确定要取消合并吗？')) {
                try {
                    await fetch(`/api/batch/cancel-task/${currentTaskId}`, {
                        method: 'POST'
                    });
                    
                    clearInterval(progressUpdateInterval);
                    currentTaskId = null;
                    showStep(3);
                    
                } catch (error) {
                    alert('取消失败: ' + error.message);
                }
            }
        }

        function showCompletionStep(status) {
            const validFileCount = videoFiles.filter(f => f.is_valid).length;
            const totalDuration = formatDuration(status.total_duration || 0);
            
            document.getElementById('completion-summary').textContent = 
                `成功合并了 ${validFileCount} 个视频文件，总时长 ${totalDuration}`;
            
            showStep(5);
        }

        async function continueToAI() {
            if (!currentTaskId) {
                alert('没有可用的合并任务');
                return;
            }

            try {
                showLoading('正在准备进入AI处理流程...');
                
                const response = await fetch(`/api/batch/continue-to-main-flow/${currentTaskId}`, {
                    method: 'POST'
                });

                const data = await response.json();
                
                if (response.ok) {
                    // 将合并后的视频信息传递到主页面
                    const videoInfo = {
                        path: data.video_path,
                        filename: data.filename,
                        size: data.file_size
                    };
                    
                    // 使用URL参数传递视频信息
                    const params = new URLSearchParams({
                        merged_video: JSON.stringify(videoInfo),
                        from_batch: 'true'
                    });
                    
                    // 跳转到主页面
                    window.location.href = `/?${params.toString()}`;
                } else {
                    throw new Error(data.detail || '获取合并视频信息失败');
                }
                
            } catch (error) {
                alert('进入AI流程失败: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        function toggleBackgroundMusic() {
            const checkbox = document.getElementById('add-background-music');
            const options = document.getElementById('background-music-options');
            
            if (checkbox.checked) {
                options.style.display = 'block';
            } else {
                options.style.display = 'none';
            }
        }
        
        function updateVolumeDisplay() {
            const slider = document.getElementById('music-volume');
            const display = document.getElementById('volume-display');
            display.textContent = slider.value + '%';
        }

        function newBatch() {
            // 重置所有状态
            currentTaskId = null;
            videoFiles = [];
            scanSummary = {};
            
            if (progressUpdateInterval) {
                clearInterval(progressUpdateInterval);
                progressUpdateInterval = null;
            }
            
            // 清空输入
            document.getElementById('folder-path').value = '/Users/v9/Documents/workspace/v9/code/banyun/videos/0722/0722-cat-video-v1';
            document.getElementById('recursive-scan').checked = false;
            document.getElementById('output-filename').value = 'merged_video.mp4';
            document.getElementById('merge-quality').value = 'original';
            document.getElementById('add-background-music').checked = false;
            document.getElementById('background-music-file').value = '';
            document.getElementById('music-volume').value = 30;
            document.getElementById('music-start-time').value = 0;
            document.getElementById('music-fade').value = 'in';
            updateVolumeDisplay();
            toggleBackgroundMusic();
            
            // 返回第一步
            showStep(1);
        }

        function showStep(stepNumber) {
            // 隐藏所有步骤
            for (let i = 1; i <= 5; i++) {
                document.getElementById(`step${i}`).style.display = 'none';
            }
            
            // 显示指定步骤
            document.getElementById(`step${stepNumber}`).style.display = 'block';
        }

        function showLoading(message) {
            // 简单的加载指示器
            const btn = event.target;
            if (btn) {
                btn.disabled = true;
                btn.textContent = message;
            }
        }

        function hideLoading() {
            // 恢复按钮状态
            document.getElementById('scan-folder').disabled = false;
            document.getElementById('scan-folder').textContent = '🔍 扫描文件夹';
        }

        // 工具函数
        function formatDuration(seconds) {
            if (!seconds || seconds <= 0) return '0:00';
            
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = Math.floor(seconds % 60);
            
            if (hours > 0) {
                return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            } else {
                return `${minutes}:${secs.toString().padStart(2, '0')}`;
            }
        }

        function formatFileSize(bytes) {
            if (!bytes || bytes <= 0) return '0 B';
            
            const units = ['B', 'KB', 'MB', 'GB'];
            let size = bytes;
            let unitIndex = 0;
            
            while (size >= 1024 && unitIndex < units.length - 1) {
                size /= 1024;
                unitIndex++;
            }
            
            return `${size.toFixed(1)} ${units[unitIndex]}`;
        }

        function getSortMethodName(method) {
            const names = {
                'natural': '智能排序',
                'filename': '文件名排序',
                'date_created': '创建时间',
                'date_modified': '修改时间',
                'size': '文件大小',
                'duration': '视频时长'
            };
            return names[method] || '未知方法';
        }

        // 更新视频速率
        function updateVideoSpeed(index, speed) {
            if (index >= 0 && index < videoFiles.length) {
                // 限制速率范围
                speed = Math.max(0.25, Math.min(4.0, speed));
                videoFiles[index].speed = speed;
                
                // 更新汇总信息中的总时长
                updateTotalDuration();
            }
        }

        // 更新总时长显示（考虑速率调整）
        function updateTotalDuration() {
            let totalAdjustedDuration = 0;
            videoFiles.forEach(file => {
                if (file.is_valid && file.duration > 0) {
                    totalAdjustedDuration += file.duration / (file.speed || 1.0);
                }
            });
            
            const durationElement = document.getElementById('total-duration');
            if (durationElement) {
                durationElement.textContent = formatDuration(totalAdjustedDuration);
            }
        }

        // 批量设置速率
        function setBatchSpeed() {
            const speed = prompt('请输入要批量设置的速率（0.25-4.0）:', '1.0');
            if (speed !== null) {
                const speedValue = parseFloat(speed);
                if (speedValue >= 0.25 && speedValue <= 4.0) {
                    videoFiles.forEach((file, index) => {
                        if (file.is_valid) {
                            file.speed = speedValue;
                        }
                    });
                    displayVideoList(videoFiles);
                    updateTotalDuration();
                } else {
                    alert('速率必须在0.25到4.0之间');
                }
            }
        }
    </script>
</body>
</html>